import React, { useEffect, useState, useRef } from 'react'
import NewsEditor from '../../../comopnents/news-manage/NewsEditor'
import style from './News.module.css'
import { PageHeader, Steps, Button, Form, Select, Input, message, notification } from 'antd';
import axios from 'axios';
const { Step } = Steps;
const { Option } = Select

export default function NewsUpdate(props) {
  const [current, setCurrent] = useState(0)
  const [categoryList, setCategoryList] = useState([])
  const [formInfo, setFormInfo] = useState({})
  const [content, setContent] = useState("")

  const User = JSON.parse(localStorage.getItem("token"))
  // 下一步按钮
  const handleNext = () => {
    if (current === 0) {
      // ref里面有一个validateFields方法里面有一个then成功去返回；有个catch失败去返回
      NewsFrom.current.validateFields().then(res => {
        // console.log(res);
        setFormInfo(res)
        setCurrent(current + 1)
      }).catch(error => {
        console.log(error);
      })
    } else {
      // 判断内容不能为空
      if (content === '') {
        message.error("新闻内容不能为空喔！！！")
      } else {

      }
      setCurrent(current + 1)
    }
  }

  // 上一步按钮
  const handlePrevious = () => {
    setCurrent(current - 1)
  }

  const layout = {
    labelCol: { span: 2 },
    wrapperCol: { span: 22 },
  };

  const NewsFrom = useRef(null)

  useEffect(() => {
    axios.get("/categories").then(res => {
      // console.log(res)
      setCategoryList(res.data)
    })
  }, [])

  useEffect(() => {
    // console.log(props.match.params.id);
    axios.get(`/news/${props.match.params.id}?_expand=category&_expand=role`).then(res => {
      // 把相应的文章信息存上去
      // setNewSInfo(res.data)
      let { title, categoryId, content } = res.data
      NewsFrom.current.setFieldsValue({
        title,
        categoryId
      })
      setContent(content)
    })
  }, [props.match.params.id])

  ////保存草稿箱 -- 通过auditState点击传入的函数（handleSave(0)）去判断。
  const handleSave = (auditState) => {
    axios.post("/news", {
      ...formInfo,
      "content": content,
      "region": User.region ? User.region : "全球",
      "author": User.username,
      "roleId": User.roleId,
      "auditState": auditState,
      "publishState": 0,
      "createTime": Date.now(),
      "star": 0,
      "view": 0,
      // "id": 1,
      // "publishTime": 0
    }).then(res => {
      props.history.push(auditState === 0 ? '/news-manage/draft' : '/audit-manage/list')
      notification.info({
        message: `通知`,
        description: `您可以到${auditState === 0 ? '草稿箱' : '审核列表'}中查看你的新闻`,
        placement: 'bottomRight',
      });
    })
  }
  return (
    <div>
      <PageHeader
        onBack={() => window.history.back()}
        className="site-page-header"
        title="更新新闻"
      />
      <Steps current={current}>
        <Step title="基本信息" description="新闻标题，新闻分类" />
        <Step title="新闻内容" description="新闻主题内容" />
        <Step title="新闻提交" description="保存草稿或者提交审核" />
      </Steps>

      <div style={{ marginTop: "50px" }}>
        <div className={current === 0 ? '' : style.active}>
          <Form {...layout} ref={NewsFrom}>
            <Form.Item name="title" label="新闻标题" rules={[{ required: true }]}>
              <Input />
            </Form.Item>
            <Form.Item name="categoryId" label="新闻分类" rules={[{ required: true }]}>
              <Select allowClear>
                {
                  categoryList.map(Item =>
                    <Option value={Item.id} key={Item.id}>{Item.title}</Option>
                  )
                }
              </Select>
            </Form.Item>
          </Form>
        </div>
      </div>
      <div className={current === 1 ? '' : style.active}>
        <NewsEditor getContent={(value) => {
          // console.log(value);
          setContent(value)
        }} content={content}></NewsEditor>
      </div>
      <div className={current === 2 ? '' : style.active}></div>

      <div style={{ marginTop: "50px" }}>
        {
          current === 2 && <span>
            <Button type="primary" onClick={() => handleSave(0)}>保存草稿箱</Button>
            <Button danger onClick={() => handleSave(1)}>提交审核</Button>
          </span>
        }
        {
          current < 2 && <Button type="primary" onClick={handleNext}>下一步</Button>
        }
        {
          current > 0 && <Button onClick={handlePrevious}>上一步</Button>
        }
      </div>
    </div>
  )
}
